home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1997 January: Mac OS SDK / Dev.CD Jan 97 SDK2.toast / Development Kits (Disc 2) / ScriptX / Documentation / Code Examples from Docs / langguid / chap_05 / xmpl_04.sx < prev    next >
Encoding:
Text File  |  1996-05-21  |  1.6 KB  |  73 lines  |  [TEXT/ttxt]

  1. --<<<
  2. -- Kaleida Labs, Inc.
  3. -- Field Guide to the ScriptX Language
  4. -- chapter 5, example 4
  5.  
  6. -- create a module to avoid naming conflicts
  7. module Scratch18 uses ScriptX end
  8. in module Scratch18
  9.  
  10. -- anonymous functions examples
  11. -- declare globals
  12. global cubeMe, reagan, speech, myCounter, anotherCounter
  13.  
  14. (n -> n * n )
  15. (a b -> a + b )
  16. (#rest nums -> for i in nums do print (i * 10))
  17.  
  18. function addtwo a b -> a + b
  19. addtwo 4 5
  20. (a b -> a + b ) 4 5
  21.  
  22. for i in #(1,2,3,4) collect (n -> n * n) i
  23.  
  24. cubeMe := (a -> a * a * a)
  25. cubeMe 2
  26.  
  27. -- this is OK
  28. function sumTheNum arg -> (
  29.     if arg <= 0 then return 0
  30.     else return (arg + (sumTheNum (arg - 1)))
  31. )
  32. sumTheNum 2
  33. sumTheNum 10
  34.  
  35. -- not an efficient way to do recursion
  36. sumTheNum2 := (arg -> (
  37.     if arg = 0 then return 0
  38.     else return (arg + (sumTheNum2 (arg - 1)))
  39. ))
  40.  
  41. -- even an actor can be president
  42. global reagan := new String string:""
  43. global speech := "Facts are stupid things"
  44. for i in speech collect into reagan by \
  45.     (sequence value -> prepend sequence value; sequence) i
  46.  
  47. -- examples of closures
  48. function closureMaker -> (
  49.     -- x is the free variable or closure variable
  50.     local x := theCalendarClock.time
  51.     -- elapsedTime is the function that will be returned as a closure
  52.     local fn elapsedTime -> (
  53.         local result := theCalendarClock.time - x
  54.         x := theCalendarClock.time
  55.         result
  56.     )
  57.     -- the next expression is the return value of this function
  58.     -- it returns the local function elapsedTime
  59.     -- that turns it into a closure
  60.     elapsedTime
  61. )
  62. timeKeeper := closureMaker()
  63. timeKeeper()
  64.  
  65. function counter -> (local x:0; (-> x := x + 1))
  66. myCounter := counter()
  67. myCounter()
  68. myCounter()
  69. myCounter()
  70.  
  71. global anotherCounter := counter()
  72. anotherCounter()
  73. -->>>